package io.gbznt.modules.buss.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import io.gbznt.common.utils.DateUtils;
import io.gbznt.common.utils.PageUtils;
import io.gbznt.common.utils.R;
import io.gbznt.common.utils.ShiroUtils;
import io.gbznt.common.validator.ValidatorUtils;
import io.gbznt.common.validator.group.AddGroup;
import io.gbznt.modules.buss.constatnt.ProcessStateEnum;
import io.gbznt.modules.buss.entity.BussFarmlandInfoEntity;
import io.gbznt.modules.buss.entity.BussInspectionPlanEntity;
import io.gbznt.modules.buss.entity.BussInspectionTaskEntity;
import io.gbznt.modules.buss.entity.BussMaintainTaskEntity;
import io.gbznt.modules.buss.service.BussFarmlandInfoService;
import io.gbznt.modules.buss.service.BussInspectionPlanService;
import io.gbznt.modules.buss.service.BussInspectionTaskService;
import io.gbznt.modules.sys.entity.SysDeptEntity;
import io.gbznt.modules.sys.entity.SysUserEntity;
import io.gbznt.modules.sys.service.SysDeptService;
import io.gbznt.modules.sys.service.SysUserService;



/**
 * 巡检任务
 *
 * @author gbznt
 * @email http://www.gbznt.com/
 * @date 2019-04-20 15:48:34
 */
@RestController
@RequestMapping("buss/bussinspectiontask")
public class BussInspectionTaskController {
    @Autowired
    private BussInspectionTaskService bussInspectionTaskService;
    @Autowired
    private SysUserService sysuser;
    @Autowired
    private BussFarmlandInfoService binfo;
    
    @Autowired
    private BussInspectionPlanService bussInspectionPlanService;
    @Autowired
    private SysDeptService sysdept;
    

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("buss:bussinspectiontask:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = bussInspectionTaskService.queryPage(params);

        return R.ok().put("page", page);
    }
    
    /**
     * 所属基地
     */
    @RequestMapping("/jdlist")
    //@RequiresPermissions("buss:bussinspectiontask:list")
    public R jdlist(@RequestParam Map<String, Object> params){
        PageUtils page = bussInspectionTaskService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("buss:bussinspectiontask:info")
    public R info(@PathVariable("id") String id){
        BussInspectionTaskEntity bussInspectionTask = bussInspectionTaskService.getById(id);
      //巡检人
    	String xjr = bussInspectionTask.getHandler();
    	if(StringUtils.isNotBlank(xjr)){
    		SysUserEntity sysusere =  sysuser.getById(xjr);
    		if(sysusere!=null){
    			bussInspectionTask.setHandlername(sysusere.getName());
    		}
    		
    	}
    	//基地名称
    	String jd = bussInspectionTask.getDeptId();
    	if(StringUtils.isNotBlank(jd)){
    		SysDeptEntity sysusere =  sysdept.getById(jd);
    		if(sysusere!=null){
    			bussInspectionTask.setDeptIdname(sysusere.getName());
    		}
    		
    	}
    	//田块名称
    	String tk = bussInspectionTask.getFarmlandInfoIds();
    	String tkname = "";
    	if(StringUtils.isNotBlank(tk)){
    		/*String string=tk;
    		String substring = string.substring(0, string.length()-1);//截取最后一个
    		System.out.println(substring);
    		String[] split = substring.split(",");//以逗号分割
    		System.out.println(split.length);
    		for (int i = 0; i < split.length; i++) {
				if(i == 0){
					tkname = split[i];
					
				}else{
					tkname = tkname +","+split[i];
				}
    		
    		}*/
    		List<BussFarmlandInfoEntity> brentity = binfo.list(
					new QueryWrapper<BussFarmlandInfoEntity>().in("id", tk.split(","))
			);
    		for (int i = 0; i < brentity.size(); i++) {
    			if(i == 0){
					tkname = brentity.get(i).getName();
					
				}else{
					tkname = tkname +","+brentity.get(i).getName();
				}
			}
    		
    		bussInspectionTask.setFarmlandInfoIdsname(tkname);
    	}
        return R.ok().put("bussInspectionTask", bussInspectionTask);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("buss:bussinspectiontask:save")
    public R save(@RequestBody BussInspectionTaskEntity bussInspectionTask){
    	//新增为当前时间-
    	//status
    	if("2".equals(bussInspectionTask.getStatus())){
    		bussInspectionTask.setFinishTime(new Date());
    	}
    	// 生成工号
		String ymdStr = DateUtils.format(new Date(), "yyyyMMdd");// 年月日
		String businessNum = ymdStr + "X0001";
		BussInspectionTaskEntity lastBussMaintainTaskEntity = bussInspectionTaskService
				.getOne(new QueryWrapper<BussInspectionTaskEntity>().select("max(business_num) as business_num")
						.like("business_num", ymdStr));
		if (null != lastBussMaintainTaskEntity) {
			String lastNumStr = lastBussMaintainTaskEntity.getBusinessNum().substring(9);
			Integer lastNum = Integer.valueOf(lastNumStr) + 1;
			businessNum = ymdStr + "X" + String.format("%04d", lastNum);
		}
		bussInspectionTask.setBusinessNum(businessNum);
    	//设置为自动添加
    	bussInspectionTask.setSourceType(0);
    	ValidatorUtils.validateEntity(bussInspectionTask,AddGroup.class);
    
   	 	bussInspectionTask.setCreateId(ShiroUtils.getUserId()+"");
    	bussInspectionTask.setCreateTime(new Date());
    	//手动添加数据 部门为当前人部门
    	//bussInspectionTask.setDeptId(ShiroUtils.getUserEntity().getDeptId());
        bussInspectionTaskService.save(bussInspectionTask);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("buss:bussinspectiontask:update")
    public R update(@RequestBody BussInspectionTaskEntity bussInspectionTask){
//    	if(bussInspectionTask.getStatus()!=null){
//    		if(bussInspectionTask.getStatus() == 2){
//        		bussInspectionTask.setFinishTime(new Date());
//        	}	
//    	}
    	
        ValidatorUtils.validateEntity(bussInspectionTask,AddGroup.class);
       
        bussInspectionTask.setUpdateId(ShiroUtils.getUserId()+"");
    	bussInspectionTask.setUpdateTime(new Date());
    	// 填入接收时间与完成时间
        if(bussInspectionTask.getStatus() == ProcessStateEnum.PROCESSING.getValue()){
        	bussInspectionTask.setReceiveTime(new Date());
        }else if(bussInspectionTask.getStatus() == ProcessStateEnum.FINISH.getValue()){
        	bussInspectionTask.setFinishTime(new Date());
        }
    	
        Boolean re = bussInspectionTaskService.updateById(bussInspectionTask);//全部更新
        
        return re?R.ok():R.oldVersion();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("buss:bussinspectiontask:delete")
    public R delete(@RequestBody String[] ids){
        bussInspectionTaskService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

	
	/**
	 * 修改
	 */
	@RequestMapping("changeStatus/{id}/{status}")
	@RequiresPermissions("buss:bussinspectionplan:update")
	public R changeStatus(@PathVariable("id") String id,@PathVariable("status") String status) {
		//ValidatorUtils.validateEntity(bussInspectionPlan, AddGroup.class);
		BussInspectionPlanEntity bussInspectionPlan = bussInspectionPlanService.getById(id);
		bussInspectionPlan.setStatus(Integer.parseInt(status));
		
		bussInspectionPlan.setUpdateId(ShiroUtils.getUserId() + "");
		bussInspectionPlan.setUpdateTime(new Date());
		bussInspectionPlan.setUpdateName(ShiroUtils.getUserName());
		Boolean re = bussInspectionPlanService.updateById(bussInspectionPlan);// 全部更新

		return re ? R.ok() : R.oldVersion();
	}
}
